const runtime = require('postman-runtime');
var runner = new runtime.Runner(); // 
let {errCode} = require('../controllers/code');
var fs = require('fs'), // needed to read JSON file from disk
    Collection = require('postman-collection').Collection,
    myCollection;
// a collection object constructed using the Postman Collection SDK.
let run  = (obj)=>{
    myCollection = new Collection(obj);
    return new Promise((resolve,reject)=>{
        runReq(resolve,reject,myCollection);
    })
}

function runReq(resolve,reject,myCollection){
    var data = {};
    data.tests = []
    runner.run(myCollection, { /* options */ }, function(err, run) {
        run.start({
            assertion: function (cursor, assertions) {
                data.tests.push(assertions)//tests是每个结果运行一次，只有一个接口传入的时候会循环调用，循环导入数组即可。                 
                 //console.log(assertions);
            },
    
            // Called once with response for each request in a collection
            response: function (err, cursor, response, request, item, cookies, history) {
                //console.log(JSON.stringify(response))
                
                // err, cursor: Same as arguments for "start"
                // item: sdk.Item
                data.response = response;
                if(response && response.stream){
                    data.response.stream = JSON.parse(response.stream.toString());
                    //data.response.cookies = cookies;
                    //console.log(cookies);
                    data.code = errCode.SUCCESS;
                }else{
                    data.code = errCode.INTERFACE_ADDRESS_INVALID;
                }
                // response: sdk.Response
                // request: sdk.request
            },    
            // Called at the end of a run
            done: function (err) {
                if(err){
                    reject({
                        code : errCode.SYSTEM_INNER_ERROR
                    })
                }else{
                    // err: null or Error
                    console.log(err);
                    console.log('done');
                    if(!data.code){
                        data.code = errCode.SYSTEM_INNER_ERROR;
                    }
                    resolve(data);
                }
            },
            // Called any time a console.* function is called in test/pre-request scripts
            console: function (cursor, level, ...logs) {}
        });
    });
}

module.exports = {
    run
}